@page "/Review"
@using System.Net
@using System.Text.Json
@using MeiwenDiaryWeb.Components.Controls
@using MeiwenDiaryWeb.Models
@inject SwalService _swalService

<PageTitle>日记回顾</PageTitle>

<div style="height: 12px"></div>

<Timeline Items="@_timelineItems" IsAlternate="true"></Timeline>

<div style="height: 12px"></div>

<div class="text-center">
    <Button OnClick="LoadMoreAsync" style="display: inline-block">加载更多
    </Button>
</div>

<div style="height: 12px"></div>

@code {

    public Review() {
        _start = DateTime.Today;
        if (_start.DayOfWeek != 0) {
            _start = _start.AddDays(0 - (int)_start.DayOfWeek);
        }
    }

    private DateTime _start;

    private List<TimelineItem> _timelineItems = new();

    protected async override Task OnInitializedAsync() {
        await LoadMoreAsync();
    }

    private async Task LoadMoreAsync() {
        using var httpClient = new HttpClient();

        for (var _ = 0; _ < 20; _++) {
            var since = _start.AddDays(-6);
            var to = _start;

            HttpResponseMessage response;
            try {
                response = await httpClient.GetAsync($"http://localhost:35210/summaries?sinceYear={since.Year}&sinceMonth={since.Month}&sinceDayOfMonth={since.Day}&toYear={to.Year}&toMonth={to.Month}&toDayOfMonth={to.Day}");
            } catch (Exception e) {
                await _swalService.Show(new SwalOption { Content = e.Message, Category = SwalCategory.Error });
                return;
            }

            var summaryViewModel = response.StatusCode == HttpStatusCode.NotFound
                ? new SummaryViewModel {
                    Id = -1,
                    SinceYear = since.Year,
                    SinceMonth = since.Month,
                    SinceDayOfMonth = since.Day,
                    ToYear = to.Year,
                    ToMonth = to.Month,
                    ToDayOfMonth = to.Day
                }
                : JsonSerializer.Deserialize<SummaryViewModel>(await response.Content.ReadAsStringAsync(), options: new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
            _timelineItems.Add(new TimelineItem { Component = BootstrapDynamicComponent.CreateComponent<TimelineReviewControl>(new Dictionary<string, object?> { ["SummaryViewModel"] = summaryViewModel }) });

            _start = _start.AddDays(-7);
        }
    }

}